/**
 * Created by zhouli on 18/3/13
 * Email li.zhou@huilianyi.com
 */
// 成本中心扩展字段
import React from 'react';
import {connect} from 'react-redux';
import CCEFService from 'containers/setting/cost-center/cost-center-extend-filed/cost-center-extend-filed.service';
import 'styles/setting/cost-center/cost-center-extend-filed/cost-center-extend-filed.scss';
import ExtendFieldComponent from 'components/template/extend-field-setting/extend-field';
import {
  message
} from 'antd';
import {deepFullCopy, messages} from 'share/common';
import menuRoute from 'routes/menuRoute';

const extendFieldDefault = {
  formName: '成本中心附加信息', // 成本中心项附加信息
  iconName: 'cost_center_info',
  messageKey: 'cost_center_form',
  formType: 6001,
  formCode: 'cost_center_form',
  asSystem: false,
  valid: true,
  parentOID: null,
  associateExpenseReport: false,
  customFormFields: [],
  remark: '成本中心附加信息', // 成本中心项附加信息
  referenceOID: null,
  visibleExpenseTypeScope: 1001,
  visibleUserScope: 1001
};
// 待添加的字段类型
let customFromOriginList = [];

class CostCenterExtendFiled extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      CostCenterDetail: menuRoute.getRouteItem('cost-center-detail', 'key'), // 成本中心详情
      costCenterExtendFiled: menuRoute.getRouteItem('cost-center-extend-filed', 'key'), // 成本中心扩展字段
      isNeedNew: false, // 是否需要新增
      loading: true,
      data: [],
      customFromOriginList: [], // 可以选择表单类型
      customFrom: {}, // 配置的表单
    };
  }

  componentWillMount() {
  }

  componentDidMount() {
    this.getWidgetList();
  }

  // 获取表单字段类型
  getWidgetList = () => {
    CCEFService.getWidgetList({type: 1005})
      .then((res) => {
        customFromOriginList = res.data;
        this.getCustomForm();
      });
  }
  // 创建或者更新入口
  createOrUpdate = (form) => {
    const isNeedNew = this.state.isNeedNew;
    if (isNeedNew) {
      this.createCustomForm(form);
    } else {
      this.updateCustomForm(form);
    }
  }
  // 创建表单
  createCustomForm = (form) => {
    this.setState({
      loading: true,
    });
    console.log('costOid', this.props.params.costOid);
    CCEFService.createCustomForm(form, this.props.params.costOid)
      .then((res) => {
        message.success(messages('setting.key312'/* 更新成功*/));
        const {costCenterExtendFiled} = this.state;
        const infoData = res.data;
        const url = costCenterExtendFiled.url.replace(':costOid', this.props.params.costOid);
        const _url = url.replace(':formOID', infoData.formOID ? infoData.formOID : 'NEW');
        console.log('infoData', infoData);
        this.context.router.push(_url);
        this.getCustomForm();
      })
      .catch((res) => {
        this.setState({
          loading: false
        });
      });
  }
  // 更新表单
  updateCustomForm = (form) => {
    this.setState({
      loading: true,
    });
    CCEFService.updateCustomForm(form)
      .then((res) => {
        message.success(messages('setting.key312'/* 更新成功*/));
        this.getCustomForm();
      })
      .catch((res) => {
        this.setState({
          loading: false
        });
      });
  }
  // 取消
  cancel = () => {
    const {CostCenterDetail} = this.state;
    this.context.router.push(CostCenterDetail.url.replace(':id', this.props.params.costOid));
  }
  // 设置 customFormFieldI18nDTOS，后端改变结构，没有返回 customFormFieldI18nDTOS
  setCustomFormFieldI18nDTOS = (originCustomFormFields) => {
    const nowWidget = originCustomFormFields;
    // counterFlag为内部组件排序所需key值，在此处初始化
    nowWidget.map((widget, index) => {
      // 添加一个 fieldCodeForDisabled 主要用来实现有编码不能编辑的功能
      widget.fieldCodeForDisabled = widget.fieldCode;
      // 联动开关要用
      if (!widget.customFormFieldI18nDTOS || widget.customFormFieldI18nDTOS.length === 0) {
        widget.customFormFieldI18nDTOS = [];
        this.props.languageList.map((language) => {
          const i18nDTO = {
            fieldName: widget.fieldName,
            promptInfo: widget.promptInfo,
            language: language.code
          };
          widget.customFormFieldI18nDTOS.push(i18nDTO);
        });
      }
      if (!widget.i18n) {
        widget.i18n = {};
      }
      if (!widget.i18n.fieldName || !widget.i18n.fieldName.length) {
        const fieldNameI18n = [];
        this.props.languageList.map((language) => {
          const i18nDTO = {
            language: language.code,
            value: widget.fieldName ? widget.fieldName : ''
          };
          fieldNameI18n.push(i18nDTO);
        });
        widget.i18n.fieldName = fieldNameI18n;
      }
      if (!widget.i18n.promptInfo || !widget.i18n.promptInfo.length) {
        const promptInfoI18n = [];
        this.props.languageList.map((language) => {
          const i18nDTO = {
            language: language.code,
            value: widget.promptInfo ? widget.promptInfo : ''
          };
          promptInfoI18n.push(i18nDTO);
        });
        widget.i18n.promptInfo = promptInfoI18n;
      }
      return widget;
    });
  }
  // 获取表单
  getCustomForm = () => {
    console.log('formOID查询表单', this.props.params.formOID);
    const {params} = this.props;
    console.log(params);
    if (params.formOID === 'NEW') {
      this.setState({
        isNeedNew: true,
        loading: false,
        customFromOriginList,
        customFrom: deepFullCopy(extendFieldDefault)
      });
    } else {
      CCEFService.getCustomFormRefactoring(this.props.params.formOID)
        .then((res) => {
          if (res.data === '' || res.data === undefined || res.data === null) {
            // 没有获取到表单
            message.warn(messages('setting.key313'/* 没有获取到表单*/));
            return;
          }
          if (res.data) {
            const customFrom = res.data;
            if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
              this.setCustomFormFieldI18nDTOS(customFrom.customFormFields);
            }
            if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
              customFrom.customFormFields[0]._active = true;
            }
            this.setState({
              isNeedNew: false,
              loading: false,
              customFrom,
              customFromOriginList,
            });
          } else {
            this.setState({
              isNeedNew: true,
              loading: false,
              customFromOriginList,
              customFrom: deepFullCopy(extendFieldDefault)
            });
          }
        })
        .catch((res) => {
          this.setState({
            loading: false
          });
        });
    }

  }

  render() {
    const {loading, customFrom, customFromOriginList} = this.state;
    const {tenantMode} = this.props;
    return (
      <div className="cost-center-extend-filed">
        <ExtendFieldComponent
          loading={loading}
          filedMax={10}
          cancel={this.cancel}
          rightIsShow={tenantMode}
          bottomBtnIsShow={tenantMode}
          leftDragable={tenantMode}
          saveFrom={this.createOrUpdate}
          customFrom={customFrom}
          customFromOriginList={customFromOriginList}
        />
      </div>
    );
  }
}

CostCenterExtendFiled.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    language: state.main.language,
    languageList: state.login.languageList,
  };
}

export default connect(mapStateToProps)(CostCenterExtendFiled);
